<!-- family_id 和 role_type 暂时没有设置 等待完善。 -->
<template>
  <el-container direction="vertical" class="user-management">
    <!-- 查询面板 -->
    <QueryPanel
      v-model="queryForm"
      :fields="queryFields"
      :actions="queryActions"
      @action="handleQueryAction"
    />
    
    <!-- 用户列表 -->
    <DataTable
      :data="userList"
      :loading="loading"
      :columns="tableColumns"
      :pagination="pagination"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
    >
      <template #status="{ row }">
        <el-tag :type="row.is_active ? 'success' : 'danger'">
          {{ row.is_active ? '启用' : '禁用' }}
        </el-tag>
      </template>
      
      <template #permissions="{ row }">
        <el-tag :type="row.is_superuser ? 'danger' : 'info'">
          {{ row.is_superuser ? '管理员' : '用户' }}
        </el-tag>
      </template>
      
      <template #actions="{ row }">
        <el-button link type="primary" size="small" @click="handleEdit(row)">
          编辑
        </el-button>
        <el-button link type="danger" size="small" @click="handleDelete(row)">
          删除
        </el-button>
      </template>
    </DataTable>
    
    <!-- 用户表单对话框 -->
    <FormDialog
      v-model:visible="dialogVisible"
      :title="isEdit ? '编辑用户' : '添加用户'"
      :model-value="userForm"
      :fields="formFields"
      :rules="formRules"
      :loading="saving"
      @submit="saveUser"
      @close="resetForm"
    />
  </el-container>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import QueryPanel from '@/components/query/QueryPanel.vue'
import DataTable from '@/components/table/DataTable.vue'
import FormDialog from '@/components/page/FormDialog.vue'
import { userApi, type UserInfo, type UserQuery } from '@/api/base/user'

// 查询表单
const queryForm = reactive<UserQuery>({
  page: 1,
  pageSize: 10,
  username: '',
  email: '',
  family_id: undefined
})

// 查询字段配置
const queryFields = [
  {
    prop: 'username',
    label: '用户名',
    type: 'input' as const,
    placeholder: '请输入用户名'
  },
  {
    prop: 'email',
    label: '邮箱',
    type: 'input' as const,
    placeholder: '请输入邮箱'
  }
]

// 查询操作按钮
const queryActions = [
  { name: 'search', label: '查询', type: 'primary' as const },
  { name: 'reset', label: '重置', type: '' as const },
  { name: 'add', label: '添加用户', type: 'success' as const }
]

// 表格列配置
const tableColumns = [
  { prop: 'username', label: '用户名', minWidth: '120' },
  { prop: 'email', label: '邮箱', minWidth: '180' },
  { prop: 'nickname', label: '昵称', minWidth: '100' },
  { prop: 'is_active', label: '状态', width: '80', slot: 'status' },
  { prop: 'is_superuser', label: '权限', width: '80', slot: 'permissions' }
]

// 表单字段配置
const formFields = [
  {
    prop: 'username',
    label: '用户名',
    type: 'input' as const,
    placeholder: '请输入用户名',
    props: { disabled: false }
  },
  {
    prop: 'email',
    label: '邮箱',
    type: 'input' as const,
    placeholder: '请输入邮箱'
  },
  {
    prop: 'nickname',
    label: '昵称',
    type: 'input' as const,
    placeholder: '请输入昵称'
  },
  {
    prop: 'is_active',
    label: '状态',
    type: 'switch' as const
  }
]

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 用户表单
const userForm = reactive({
  id :  null as number | null,
  username: '',
  email: '',
  nickname: '',
  is_active: true
})

// 数据状态
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentUserId = ref<number | null>(null)
const userList = ref<UserInfo[]>([])

// 方法
const loadUsers = async () => {
  try {
    loading.value = true
    const response = await userApi.getUserList(queryForm)
    console.log('API Response:', response) // 添加日志查看响应数据结构
    
    userList.value = response.data || []
    pagination.total = response.total || 0
    // 修复分页字段不匹配的问题
    pagination.pageSize = response.page_size || pagination.pageSize
  } catch (error) {
    console.error('获取用户列表失败:', error) // 添加错误日志
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleQueryAction = (action: string) => {
  switch (action) {
    case 'search':
      queryForm.page = 1
      loadUsers()
      break
    case 'reset':
      Object.assign(queryForm, {
        username: '',
        email: '',
        family_id: undefined,
        page: 1,
        pageSize: 10
      })
      loadUsers()
      break
    case 'add':
      showAddDialog()
      break
  }
}

const handlePageChange = (page: number) => {
  queryForm.page = page
  loadUsers()
}

const handleSizeChange = (size: number) => {
  queryForm.pageSize = size
  queryForm.page = 1
  loadUsers()
}

const showAddDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (user: UserInfo) => {
  isEdit.value = true
  currentUserId.value = user.id
  Object.assign(userForm, {
    id: user.id,  
    username: user.username,
    email: user.email,
    nickname: user.nickname,
    is_active: user.is_active
  })
  dialogVisible.value = true
}

const handleDelete = async (user: UserInfo) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户"${user.username}"吗？`, '提示', {
      type: 'warning'
    })
    
    await userApi.deleteUser(user.id)
    ElMessage.success('删除成功')
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const saveUser = async () => {
  try {
    saving.value = true
    
    if (isEdit.value && currentUserId.value) {
      await userApi.updateUser(currentUserId.value, {
        id : userForm.id,
        username: userForm.username,
        email: userForm.email,
        nickname: userForm.nickname,
        is_active: userForm.is_active,
        role_data : [{"role_type": "user","family_id": null}]
      })
      ElMessage.success('更新成功')
    } else {
      await userApi.createUser({
        id : userForm.id,
        username: userForm.username,
        email: userForm.email,
        password: '123456', // 默认密码
        nickname: userForm.nickname,
        role_data : [{"role_type": "user","family_id": null}]
      })
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadUsers()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    saving.value = false
  }
}

const resetForm = () => {
  Object.assign(userForm, {
    id : null as number | null,
    username: '',
    email: '',
    nickname: '',
    is_active: true
  })
  currentUserId.value = null
}

onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}
</style>